//
//  HomeViewController.m
//  微blog
//
//  Created by Jorn.Wu on 15/8/19.
//  Copyright (c) 2015年 Jorn.Wu(jorn_wza@sina.com). All rights reserved.
//

#import "HomeViewController.h"
#import "SinaWeiboRequest.h"
#import "SinaWeibo.h"
#import "AppDelegate.h"
#import "ThemeManager.h"
#import "HomeTableView.h"
#import "HomeWeiboFrameModel.h"
#import "HomeWeiboModel.h"
#import "UIViewController+MMDrawerController.h"
#import "MMDrawerController.h"
#import "MJRefresh.h"
#import "ThemeImageView.h"
#import "ThemeLabel.h"
#import <AudioToolbox/AudioToolbox.h>
#import "MBProgressHUD.h"
#import "WeiboDetailViewController.h"

@interface HomeViewController ()<SinaWeiboDelegate,SinaWeiboRequestDelegate,SinaWeiboDelegate,MBProgressHUDDelegate,HomeTableViewDelegate>{
    MBProgressHUD *HUD;
    NSInteger expectedLength;
    NSInteger currentLength;
}

/**
 * 新浪微博对象
 */
@property (nonatomic, strong) SinaWeibo *sinaweibo;


/**
 * 首页微博列表
 */
@property (nonatomic, strong) HomeTableView *tableView;


/**
 * 用于存储模型
 */

@property (nonatomic, strong) NSMutableArray *frameModelAr;


/**
 * 用于装载请求的新数据
 */
@property (nonatomic, strong) NSMutableArray *dataAr;


/**
 * 提示条
 */
@property (nonatomic, strong) ThemeImageView *notificationBar;
@property (nonatomic, strong) ThemeLabel *notificationLabel;


@end

@implementation HomeViewController

///---------------------------------------------------------------------------------------

/**
 ** 获取网路数据
 **/


/**
 * 获取首页微博数据的请求参数
 */

//必选	类型及范围	说明
//source	false	string	采用OAuth授权方式不需要此参数，其他授权方式为必填参数，数值为应用的AppKey。
//access_token	false	string	采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
//since_id	false	int64	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
//max_id	false	int64	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
//count	false	int	单页返回的记录条数，最大不超过100，默认为20。
//page	false	int	返回结果的页码，默认为1。
//base_app	false	int	是否只获取当前应用的数据。0为否（所有数据），1为是（仅当前应用），默认为0。
//feature	false	int	过滤类型ID，0：全部、1：原创、2：图片、3：视频、4：音乐，默认为0。
//trim_user	false	int	返回值中user字段开关，0：返回完整user字段、1：user字段仅返回user_id，默认为0。


#pragma mark - 微博请求

/**
 * 获取weibo对象
 */
- (SinaWeibo *)sinaweibo
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return delegate.sinaweibo;
}


/**
 * 加载数据
 */
- (void)loadWeiboData{
    
    _sinaweibo = [self sinaweibo];
    if ([_sinaweibo isAuthValid]) {
//        kSinaWeiboLog(@"已经登录");
        NSDictionary *params = @{@"count":@"20"};
        
        //获取微博
        [_sinaweibo requestWithURL:home_timeline
                           params:[params mutableCopy]
                       httpMethod:@"GET"
                         delegate:self];
    }else{
        
        [_sinaweibo logIn];
    }
    
}


#pragma mark - 微博请求代理

/**
 * 请求状态
 */

//1.网络请求失败
- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error {
    kSinaWeiboLog(@"网络接口请求失败：%@",error);
    [HUD hide:YES];
}


//2 网络请求成功
- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result
{
    
    NSArray *statuses = [result objectForKey:@"statuses"];
    
    NSMutableArray *tFrameModelArray = [[NSMutableArray alloc] initWithCapacity:statuses.count];
    
    for (NSDictionary *dataDic in statuses) {
        HomeWeiboModel *model = [[HomeWeiboModel alloc] initWithDataDic:dataDic];
        HomeWeiboFrameModel *frameModel = [[HomeWeiboFrameModel alloc] init];
        frameModel.weiboModel = model;
        
        [tFrameModelArray addObject:frameModel];
        
    }
    
    self.dataAr = [tFrameModelArray mutableCopy];       //一定是mutableCopy，否则frameModelAr将转会文不可变，后面不可增删等操作了
    
    /**
     * 对获取数据进行处理
     */
    if (request.tag == 100) {       //第一次请求
        
        HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]];
        [HUD hide:YES afterDelay:2];
        
        self.frameModelAr = [self.dataAr mutableCopy];      //一定是mutableCopy，否则frameModelAr将转会文不可变，后面不可增删等操作了
        //把modelArray数据传到tableView显示出来
        if (self.dataAr.count > 0) {
            _tableView.weiboFrameModelAr = [self.frameModelAr copy];
            [_tableView reloadData];
        }
        
    }else if (request.tag == 101) {     //下拉刷新
        
        if (self.dataAr.count > 1) {
//            kSinaWeiboLog(@"xia---%li",self.dataAr.count);

            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, self.dataAr.count)];
            [self.frameModelAr insertObjects:self.dataAr atIndexes:indexSet];
            _tableView.weiboFrameModelAr = [self.frameModelAr copy];
            [_tableView reloadData];
            
            
            /**
             * 显示提示条
             */
            [self showRefreshNotificotionBarWithNewWeiboCount:self.dataAr.count];
        }
        
    }else if (request.tag == 102) {     //上拉加载
                
        if (self.dataAr.count > 1) {
//            kSinaWeiboLog(@"shang---%li",self.dataAr.count);
            
            [self.dataAr removeObjectAtIndex:0];        //去掉重复的第一个
            [self.frameModelAr addObjectsFromArray:self.dataAr];
            _tableView.weiboFrameModelAr = [self.frameModelAr copy];
            [_tableView reloadData];
        }
        
    }
    
    [self.tableView.header endRefreshing];
    [self.tableView.footer endRefreshing];
    

}

- (void)request:(SinaWeiboRequest *)request didReceiveResponse:(NSURLResponse *)response{
    expectedLength = MAX([response expectedContentLength], 1);
    currentLength = 0;
    
    [HUD hide:NO];
    HUD.mode = MBProgressHUDModeDeterminate;
}
- (void)request:(SinaWeiboRequest *)request didReceiveRawData:(NSData *)data{
    currentLength += [data length];
    HUD.progress = currentLength / (float)expectedLength;
}


#pragma mark - 界面
///---------------------------------------------------------------------------------------

/**
 ** 界面搭建
 **/



- (void)viewDidLoad {
    [super viewDidLoad];
    [self createHomeTableView];
    [self loadWeiboData];
    
    [self createItems];
    
    HUD = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    HUD.delegate = self;

}

///---------- 懒加载数组 ---------

- (NSMutableArray *)dataAr{
    if (!_dataAr) {
        _dataAr = [NSMutableArray array];
    }
    return _dataAr;
}

- (NSMutableArray *)frameModelAr{
    if (!_frameModelAr) {
        _frameModelAr = [NSMutableArray array];
    }
    return _frameModelAr;
}


/**
 * 创建微博列表
 */
- (void)createHomeTableView{
    self.tableView = [[HomeTableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - 64) style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.mydelegate = self;
    
    
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshNewData)];
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

#pragma mark 进入微博正文
/**
 * 自定义的协议方法(进入微博详情)
 */
- (void)tableView:(HomeTableView *)tableView didSelectedIndex:(NSInteger)index{
    
    WeiboDetailViewController *detailVC = [[WeiboDetailViewController alloc] init];
    detailVC.weiboFrameModel = self.frameModelAr[index];
    
    [self.navigationController pushViewController:detailVC animated:YES];
}


/**
 * 下拉刷新
 */
- (void)refreshNewData{
//    kSinaWeiboLog(@"正在刷新");
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@"20" forKey:@"count"];
    
    HomeWeiboFrameModel *weiboFrame = self.frameModelAr[0];     //目前最新的微博
    NSString *sinceId = weiboFrame.weiboModel.weiboId.stringValue;
    [params setObject:sinceId forKey:@"since_id"];
    
    //获取微博
    SinaWeiboRequest *request = [_sinaweibo requestWithURL:home_timeline
                                                    params:[params mutableCopy]
                                                httpMethod:@"GET"
                                                  delegate:self];
    
    request.tag = 101;      //刷新的request标识
}


/**
 * 上拉加载
 */
- (void)loadMoreData{
//    kSinaWeiboLog(@"正在加载");
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@"20" forKey:@"count"];
    
    HomeWeiboFrameModel *weiboFrame = [self.frameModelAr lastObject];     //目前最下面
    NSString *maxId = weiboFrame.weiboModel.weiboId.stringValue;
    [params setObject:maxId forKey:@"max_id"];
    
    //获取微博
    SinaWeiboRequest *request = [_sinaweibo requestWithURL:home_timeline
                                                    params:[params mutableCopy]
                                                httpMethod:@"GET"
                                                  delegate:self];
    
    request.tag = 102;      //加载的request标识
}


/**
 * 如果有新微薄，显示提示条，和播放提示声音
 */
- (void)showRefreshNotificotionBarWithNewWeiboCount:(NSInteger)count{
    
    if (!_notificationBar) {
        
        _notificationBar = [[ThemeImageView alloc] initWithFrame:CGRectMake(0, -40, kScreenWidth, 40)];
        _notificationBar.imageName = @"timeline_notify.png";
        [self.view addSubview:_notificationBar];
        
        _notificationLabel = [[ThemeLabel alloc] initWithFrame:_notificationBar.bounds];
        _notificationBar.backgroundColor = [UIColor clearColor];
    }
    
    _notificationLabel.text = [NSString stringWithFormat:@"更新了%ld条微博",count];
    _notificationLabel.textColorName = @"Timeline_Notice_color";
    _notificationLabel.textAlignment = NSTextAlignmentCenter;
    [_notificationBar addSubview:_notificationLabel];
    
    if (count > 0) {
        [UIView animateWithDuration:1.0 animations:^{
            _notificationBar.transform = CGAffineTransformMakeTranslation(0, 40);
        } completion:^(BOOL finished) {
            [UIView setAnimationDelay:1.0];
            _notificationBar.transform = CGAffineTransformIdentity;
        }];
        
        
        /**
         * 注册为系统声音
         */
        NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"msgcome" ofType:@"wav"];
        NSURL *url = [NSURL fileURLWithPath:soundPath];
        
        SystemSoundID soundID;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);
        
        AudioServicesPlaySystemSound(soundID);
  
    }
}



/**
 * 添加左右item（用父类定义的方法）
 */
- (void)createItems{
    
    [self addNavigationItemWithOrientation:@"left" title:@"设置" image:nil action:@selector(leftItemAction)];
    [self addNavigationItemWithOrientation:@"right" title:@"编辑" image:nil action:@selector(rightItemAction)];
    
}


/**
 * 左边item的响应方法
 */
- (void)leftItemAction{
    
    MMDrawerController *mmDV =  self.mm_drawerController;
    [mmDV openDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
    
}


/**
 * 右边item的影响方法
 */
- (void)rightItemAction{
    
    MMDrawerController *mmDV =   self.mm_drawerController;
    [mmDV openDrawerSide:MMDrawerSideRight animated:YES completion:nil];
    
}



///-----------------------------------------------------------------------------------------------








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
